package tools.week03;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class MyNettyServer {

    private int port;

    public MyNettyServer(int port) {
        this.port = port;
    }

    public void run(){
        // 处理 accept socket 连接
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(2);
        // 处理具体连接的 read write 事件
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(16);
        try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 512)
                .childOption(ChannelOption.TCP_NODELAY, true)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_REUSEADDR, true)
                .childOption(ChannelOption.SO_RCVBUF, 32*1024)
                .childOption(ChannelOption.SO_SNDBUF, 32*1024)
                .childOption(EpollChannelOption.SO_REUSEPORT, true)
                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new MyHttpInitializer())
        ;


            Channel channel = b.bind(port).sync().channel();
            System.out.println("开启服务器，监听地址 http://127.0.0.1:"+port);
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        MyNettyServer myNettyServer = new MyNettyServer(8080);
        myNettyServer.run();
    }
}
